//
//  CQMessageCell.m
//  HiChat
//
//  Created by wqiong on 16/1/12.
//  Copyright © 2016年 wqiong. All rights reserved.
//

#import "CQMessageCell.h"
#import "EMChatManagerDefs.h"
#import "UIImageView+WebCache.h"

@interface CQMessageCell ()
@property (nonatomic, copy) NSString *hostUser;
@property (nonatomic, retain) CQBaseLabel *headerLabel;
@property (nonatomic, retain) CQBaseImageView *bubbleImageV;
@property (nonatomic, retain) CQBaseImageView *headImageV;

@end

@implementation CQMessageCell

- (void)dealloc
{
    [_hostUser release];
    [_message release];
    [_bubbleImageV release];
    [_headerLabel release];
    [_contentLabel release];
    [_headImageV release];
    [super dealloc];
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(nullable NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
       // [self creatSubviewsMessage:message];
    }
    return self;
}
- (void)setMessage:(EMMessage *)message
{
    if (_message != message) {
        [_message release];
        _message = [message retain];
        [self creatSubviewsMessage:message];

    }
}

+ (CGFloat)hightWithStr:(NSString *)str {
    CGRect high = [str boundingRectWithSize:CGSizeMake(280, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:20.0] forKey:NSFontAttributeName] context:nil];
    return high.size.height;
}

+ (CGFloat)widthWithStr:(NSString *)str {
    CGRect width = [str boundingRectWithSize:CGSizeMake(3, 280) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:20.0] forKey:NSFontAttributeName] context:nil];
    return width.size.height;
}

- (void)creatSubviewsMessage:(EMMessage *)message
{
    NSUserDefaults *useD = [NSUserDefaults standardUserDefaults];
    self.hostUser = [useD objectForKey:@"userName"];
    self.backgroundColor = [UIColor yellowColor];
    //时间
    self.headerLabel = [[CQBaseLabel alloc] init];
    self.headerLabel.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:self.headerLabel];
    // 是否显示时间
//    if (self.dataInternal.header)
//    {
//        self.headerLabel.hidden = NO;
//        self.headerLabel.text = self.dataInternal.header;
//    }
//    else
//    {
//        self.headerLabel.hidden = YES;
//    }
    [_headerLabel release];
    
    //接收/发送类型
 //   NSBubbleType type = self.dataInternal.data.type;
 //   CGFloat x = (![message.from isEqualToString:HostUser]) ? 60 : [UIScreen mainScreen].bounds.size.width - 80;
    CGFloat y = 5;
    id<IEMMessageBody> msgBody = message.messageBodies.firstObject;
    self.headImageV = [[CQBaseImageView alloc] init];
    self.headImageV.layer.cornerRadius = 20;
    self.headImageV.layer.masksToBounds = YES;
    if (![self.message.from isEqualToString:self.hostUser])
    {
        self.headImageV.image = [UIImage imageNamed:@"touxiang1"];
        self.headImageV.backgroundColor = [UIColor greenColor];
        self.headImageV.frame = CGRectMake(0, y + 20, 40, 40);
    } else {
        self.headImageV.image = [UIImage imageNamed:@"touxiang2"];
        self.headImageV.backgroundColor = [UIColor blueColor];
        self.headImageV.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 40, y + 20, 40, 40);
    }
    [self.contentView addSubview:self.headImageV];
    [_headImageV release];
    //对话框背景
    
    switch (msgBody.messageBodyType) {
        case eMessageBodyType_Text:
            [self textBG:message];
            break;
            
        case eMessageBodyType_Image:
            [self imageBG:message];
            break;
        
        case eMessageBodyType_Voice:
            [self voiceBG:message];
        default:
            break;
    }
}

- (void)voiceBG:(EMMessage *)message {
    id<IEMMessageBody> msgBody = message.messageBodies.firstObject;
    EMVoiceMessageBody *body = (EMVoiceMessageBody *)msgBody;
    self.bubbleImageV = [[CQBaseImageView alloc] init];
    if (![self.message.from isEqualToString:self.hostUser])
    {
        self.bubbleImageV.image = [[UIImage imageNamed:@"chat_receiver_bg@2x"] stretchableImageWithLeftCapWidth:12 topCapHeight:35];
        // self.bubbleImageV.frame = CGRectMake(x - 18, y + 20, 50, 100);
        self.bubbleImageV.frame = CGRectMake(40, 27, 80, 40);
    } else {
        self.bubbleImageV.image = [[UIImage imageNamed:@"chat_sender_bg@2x"] stretchableImageWithLeftCapWidth:12 topCapHeight:35];
        self.bubbleImageV.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 50 - 80, 27, 80, 40);
    }
    
    [self.contentView addSubview:self.bubbleImageV];
    self.contentLabel = [[CQBaseLabel alloc] init];
    self.contentLabel.numberOfLines = 0;
    self.contentLabel.font = [UIFont systemFontOfSize:20];
    self.contentLabel.frame = CGRectMake(self.bubbleImageV.frame.origin.x + 10, self.bubbleImageV.frame.origin.y + 5, 80, 40);
    self.contentLabel.textAlignment = NSTextAlignmentCenter;
    self.contentLabel.textColor = [UIColor cyanColor];
    self.contentLabel.text = [NSString stringWithFormat:@"%ld秒", (long)body.duration];
    [self.contentView addSubview:self.contentLabel];

}

- (void)textBG:(EMMessage *)message {
    self.bubbleImageV = [[CQBaseImageView alloc] init];
    CGFloat width = [[self class] widthWithStr:[message.messageBodies.firstObject text]];
    CGFloat high = [[self class] hightWithStr:[message.messageBodies.firstObject text]];
    if (![self.message.from isEqualToString:self.hostUser])
    {
        self.bubbleImageV.image = [[UIImage imageNamed:@"chat_receiver_bg@2x"] stretchableImageWithLeftCapWidth:12 topCapHeight:35];
        // self.bubbleImageV.frame = CGRectMake(x - 18, y + 20, 50, 100);
        self.bubbleImageV.frame = CGRectMake(40, 27, width + 10, high + 10);
    } else {
        self.bubbleImageV.image = [[UIImage imageNamed:@"chat_sender_bg@2x"] stretchableImageWithLeftCapWidth:12 topCapHeight:35];
        self.bubbleImageV.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 50 - width, 27, width + 10, high + 10);
    }
    
    [self.contentView addSubview:self.bubbleImageV];
    
    self.contentLabel = [[CQBaseLabel alloc] init];
    self.contentLabel.numberOfLines = 0;
    self.contentLabel.font = [UIFont systemFontOfSize:20];
    self.contentLabel.frame = CGRectMake(self.bubbleImageV.frame.origin.x + 10, self.bubbleImageV.frame.origin.y + 5, width, high);
    self.contentLabel.text = [self.message.messageBodies.firstObject text];
    [self.contentView addSubview:self.contentLabel];

}

- (void)imageBG:(EMMessage *)message {
    id<IEMMessageBody> msgBody = message.messageBodies.firstObject;
    self.bubbleImageV = [[CQBaseImageView alloc] init];
    EMImageMessageBody *body = ((EMImageMessageBody *)msgBody);
    UIImageView *imagePhoto = [[UIImageView alloc] init];
    if (![self.message.from isEqualToString:self.hostUser])
    {
        self.bubbleImageV.image = [[UIImage imageNamed:@"chat_receiver_bg@2x"] stretchableImageWithLeftCapWidth:12 topCapHeight:35];
        // self.bubbleImageV.frame = CGRectMake(x - 18, y + 20, 50, 100);
        self.bubbleImageV.frame = CGRectMake(40, 27, 150, 150);
        [imagePhoto sd_setImageWithURL:[NSURL URLWithString:body.remotePath] placeholderImage:[UIImage imageNamed:@"zhanwei.jpg"]];
        imagePhoto.frame = CGRectMake(self.bubbleImageV.frame.origin.x + 13 , self.bubbleImageV.frame.origin.y + 15, 120, 120);
    } else {
        self.bubbleImageV.image = [[UIImage imageNamed:@"chat_sender_bg@2x"] stretchableImageWithLeftCapWidth:12 topCapHeight:35];
        self.bubbleImageV.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 50 - 150, 27, 150, 150);
        imagePhoto.image = [UIImage imageNamed:body.thumbnailLocalPath];
        imagePhoto.frame = CGRectMake(self.bubbleImageV.frame.origin.x + 16 , self.bubbleImageV.frame.origin.y + 15, 120, 120);
    }
    [self.contentView addSubview:self.bubbleImageV];
    [self.contentView addSubview:imagePhoto];
    [imagePhoto release];

}

- (NSString *)timeFormatted:(long long)totalSeconds
{
    totalSeconds /= 1000.0;
    NSDate  *date = [NSDate dateWithTimeIntervalSince1970:totalSeconds];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    NSLog(@"enddate=%@",localeDate);
    NSString *time = [NSString stringWithFormat:@"%@", localeDate];
    return [time substringToIndex:19];
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.headerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.contentView);
        make.height.mas_equalTo(20);
    }];
    self.headerLabel.text = [NSString stringWithFormat:@"%lld", self.message.timestamp];
    self.headerLabel.text = [self timeFormatted:self.message.timestamp];
}


@end
